<template>
  <div class="app-container">
    <el-form :inline="true" @submit.native.prevent>
      <el-form-item>
        <el-input v-model="companyName" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="search">{{ $t('search') }}</el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          icon="el-icon-plus"
          type="primary"
          @click="showAdd"
        >{{ $t('add') }}
        </el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="companyList"
      style="width: 100%;"
      @cell-click="config"
    >
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" class="demo-table-expand">
            <el-form-item label="id:">
              <span style="color: #303133 ">{{ props.row.companyId }}</span>
            </el-form-item>
            <el-form-item :label="$t('company')+$t('keyName')+':'">
              <span style="color: #303133 ">{{ props.row.companyKey }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column :label="$t('icon')" width="50">
        <template slot-scope="scope">
          <el-image
            style="width: 40px;height: 40px;margin-top: 10px"
            :src="scope.row.iconUrl"
            fit="fit"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="companyName"
        :label="$t('name')"
      />
      <el-table-column
        width="80"
        prop="language"
        :label="$t('language')"

        :formatter="fLanguage"
      />
      <el-table-column
        width="80"
        :label="$t('status')"
      >
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.status ? 'success':'danger'"
            @click.stop="updateCompanyStatus(scope.row)"
            v-text="scope.row.status ? $t('enable'):$t('DISABLE')"
          />
        </template>
      </el-table-column>
      <el-table-column :label="$t('function')" width="450">
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-office-building"
            @click.stop="gotoChild(scope.row)"
          >{{ $t('child') }}{{ $t('company') }}
          </el-button>
          <el-button
            type="text"
            icon="el-icon-cpu"
            @click.stop="gotoDevice(scope.row)"
          >{{ $t('device') }}
          </el-button>
          <el-button
            type="text"
            icon="el-icon-user"
            @click.stop="gotoUser(scope.row)"
          >{{ $t('user') }}
          </el-button>
          <el-button
            type="text"
            icon="el-icon-s-check"
            @click.stop="gotoRole(scope.row)"
          >{{ $t('role') }}
          </el-button>
          <el-button
            type="text"
            icon="el-icon-box"
            @click.stop="gotoResource(scope.row)"
          >{{ $t('resource') }}
          </el-button>
          <el-button
            type="text"
            icon="el-icon-box"
            @click.stop="gotoSecret(scope.row)"
          >{{ $t('secret') }}
          </el-button>
          <el-button
            style="color: #f56c6c"
            type="text"
            icon="el-icon-delete"
            @click.stop="del(scope.row)"
          >{{ $t('delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin: 15px 0;text-align: right;">
      <el-pagination
        background
        :current-page.sync="currentPage"
        :page-size="pageSize"
        layout="total,sizes,prev,pager,next,jumper"
        :total="total"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      :visible.sync="dialogFormVisible"
      top="5px"
    >
      <el-form
        label-width="120px"
      >
        <el-form-item :label="$t('company')+$t('name')">
          <el-input v-model="company.companyName"/>
        </el-form-item>
        <el-form-item :label="$t('short')+$t('name')">
          <el-input v-model="company.shortCompanyName"/>
        </el-form-item>
        <el-form-item :label="$t('email')">
          <el-input v-model="company.email"/>
        </el-form-item>
        <el-form-item :label="$t('phoneNumber')">
          <el-input v-model="company.phone"/>
        </el-form-item>
        <el-form-item :label="$t('official')+$t('url')">
          <el-input v-model="company.officialUrl"/>
        </el-form-item>
        <el-form-item :label="$t('weChat')+$t('qrCodeBaseUrl')">
          <el-input v-model="company.qrCodeBaseUrl"/>
        </el-form-item>
        <el-form-item :label="$t('forReferenceInfo')">
          <el-input v-model="company.forReferenceInfo"/>
        </el-form-item>
        <el-form-item :label="$t('icon')">
          <el-upload
            ref="upload"
            :headers="headers"
            drag
            name="file"
            :action="baseURL+'/company/insert'"
            :auto-upload="false"
            :on-success="handleSuccess"
            :on-error="handleError"
            :data="company"
          >
            <i class="el-icon-upload"/>
            <div class="el-upload__text">拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </el-form-item>
        <el-form-item :label="$t('language')">
          <el-select v-model="company.language">
            <el-option :label="$t('zh')" value="zh"/>
            <el-option :label="$t('en')" value="en"/>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('enable')+$t('phone')+$t('register')">
          <el-switch
            v-model="company.enablePhoneRegister"
            :active-text="$t('open')"
            :inactive-text="$t('close')"
          />
        </el-form-item>
        <el-form-item :label="$t('enable')+$t('register')">
          <el-switch
            v-model="company.enableRegister"
            :active-text="$t('open')"
            :inactive-text="$t('close')"
          />
        </el-form-item>
        <el-form-item :label="$t('userCross')">
          <el-switch
            v-model="company.userCross"
            :active-text="$t('open')"
            :inactive-text="$t('close')"
          />
        </el-form-item>
        <el-form-item :label="$t('devicePublic')">
          <el-switch
            v-model="company.devicePublic"
            :active-text="$t('open')"
            :inactive-text="$t('close')"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('cancel') }}</el-button>
        <el-button type="primary" @click="submitUpload">{{ $t('confirm') }}</el-button>
      </div>
    </el-dialog>


    <el-dialog
      :title="company.companyName"
      :visible.sync="dialogDeviceVisible"
      top="15px"
    >
      <company-device v-if="dialogDeviceVisible" :company-id="company.companyId"/>
    </el-dialog>

  </div>
</template>

<script>
import { cancelNotice, successNotice } from '@/util/common'
import { deleteCompany, insertCompany, pageGetCompanyChild, updateCompanyStatus } from '@/api/auth/authCompanyApi'
import CompanyDevice from '@/components/CompanyDevice'
import { getCompanyId, getPageSize, getShortCompanyName, getToken } from '@/util/storage'

export default {
  name: 'ChildCompany',
  components: {
    CompanyDevice
  },
  data() {
    return {
      baseURL: window.VUE_APP_BASE_API,
      companyList: [],
      dialogFormVisible: false,
      company: {},
      currentPage: 1,
      total: 0,
      pageSize: getPageSize(),
      dialogDeviceVisible: false,
      headers: {
        'access-token': getToken()
      },
      parentCompanyId: getCompanyId(),
      companyName: null,
      parentCompanyName: getShortCompanyName()
    }
  },
  mounted() {
    const param = this.$route.query
    if (param.parentCompanyId) {
      this.parentCompanyId = param.parentCompanyId
    }
    if (param.parentCompanyName) {
      this.parentCompanyName = param.parentCompanyName
    }
    this.pageGetCompanyChild()
    this.setTagsViewTitle()
  },
  methods: {
    gotoChild(item) {
      this.$router.push({
        path: '/company/child/',
        query: { parentCompanyId: item.companyId, parentCompanyName: item.companyName }
      })
    },
    setTagsViewTitle() {
      this.tempRoute = Object.assign({}, this.$route)
      const route = Object.assign({}, this.tempRoute, {
        title: `${this.parentCompanyName}`
      })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    gotoDevice(item) {
      this.company = item
      this.dialogDeviceVisible = true
    },
    fStatus(status) {
      if (status) {
        return '活动'
      } else {
        return '注销'
      }
    },
    fLanguage(item) {
      return this.$t(item.language)
    },

    gotoUser(item) {
      this.$router.push({
        path: '/company/user/' + item.companyId,
        query: { companyId: item.companyId, companyName: item.companyName }
      })
    },
    gotoRole(item) {
      this.$router.push({
        path: '/company/role/' + item.companyId,
        query: { companyId: item.companyId, companyName: item.companyName }
      })
    },
    gotoResource(item) {
      this.$router.push({
        path: '/company/resource/' + item.companyId,
        query: { companyId: item.companyId, companyName: item.companyName }
      })
    },
    gotoSecret(item) {
      this.$router.push({
        path: '/company/secret/' + item.companyId,
        query: { companyId: item.companyId, companyName: item.companyName }
      })
    },
    config(item) {
      this.$router.push({
        path: '/company/config/' + item.companyId,
        query: { companyId: item.companyId, companyName: item.companyName }
      })
    },
    handleCurrentChange(item) {
      this.currentPage = item
      this.pageGetCompanyChild()
    },
    search() {
      this.currentPage = 0
      this.pageGetCompanyChild()
    },
    del(item) {
      const that = this
      this.$confirm(this.$t('delete') + item.companyName, this.$t('prompt'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      })
        .then(function() {
          deleteCompany({
            companyId: item.companyId
          }).then(res => {
            const { code } = res
            if (code === '200') {
              successNotice(that)
              that.pageGetCompanyChild()
            }
          })
        })
        .catch(function() {
          cancelNotice(that)
        })
    },
    updateCompanyStatus(item) {
      const that = this
      this.$confirm('改变该公司状态, 是否继续?', this.$t('prompt'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      })
        .then(function() {
          let json
          if (item.status) {
            json = {
              companyId: item.companyId,
              status: false
            }
          } else {
            json = {
              companyId: item.companyId,
              status: true
            }
          }

          updateCompanyStatus(json).then(res => {
            const { code } = res
            if (code === '200') {
              that.pageGetCompanyChild()
              successNotice(that)
            }
          })
        })
        .catch(function() {
          cancelNotice(that)
        })
    },
    pageGetCompanyChild() {
      pageGetCompanyChild({
        pageSize: this.pageSize,
        currentPage: this.currentPage,
        companyName: this.companyName,
        parentCompanyId: this.parentCompanyId
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.total = data.total
          this.companyList = data.data
        }
      })
    },
    showAdd() {
      this.company = {
        language: 'zh',
        qrCodeBaseUrl: 'https://ztn-tech.com/public/static/m/index.html',
        parentCompanyId: this.parentCompanyId
      }
      this.dialogFormVisible = true
    },

    submitUpload() {
      const that = this
      this.company = JSON.parse(JSON.stringify(this.company))
      if (this.company.companyName == null || this.company.companyName === '') {
        this.$message.error(this.$t('company'))
        return
      }
      // return
      setTimeout(() => {
        that.$refs.upload.submit()
      }, 1000)
    },
    handleSuccess(res, file, fileList) {
      successNotice(this)
      this.dialogFormVisible = false
      this.pageGetCompanyChild()
    },
    handleError(err, file, fileList) {
      this.pageGetCompanyChild()
    },
    addOrUpdate() {
      if (this.company.companyName == null || this.company.companyName === '') {
        this.$message.error(this.$t('company'))
        return
      }

      const json = {
        ...this.company
      }

      insertCompany(json).then(res => {
        const { code } = res
        if (code === '200') {
          successNotice(this)
          this.dialogFormVisible = false
          this.pageGetCompanyChild()
        }
      })
    }
  }
}
</script>
